<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <!-- 不可修改 -->
      <el-form-item label="物料" prop="materialId" >
        <MaterialInfoSelect
:disabled="formType === 'update'"
          v-model="formData.materialId"
          :options="materialOptions"
        />
      </el-form-item>
      <el-form-item label="物料号" prop="materialCode">
        <el-input 
:disabled="formType === 'update'" v-model="formData.materialCode" placeholder="请输入物料号" />
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input 
:disabled="formType === 'update'" v-model="formData.materialName" placeholder="请输入物料名称" />
      </el-form-item>
      <el-form-item label="物料类型" prop="materialType">
        <el-select 
:disabled="formType === 'update'" v-model="formData.materialType" placeholder="请选择物料类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_MATERIAL_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-select 
:disabled="formType === 'update'" v-model="formData.unit" placeholder="请选择单位">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_ASSET_UNIT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数量" prop="totalQuantity">
        <el-input v-model="formData.totalQuantity" placeholder="请输入数量" />
      </el-form-item>
      <el-form-item label="占用数量" prop="occupiedQuantity">
        <el-input v-model="formData.occupiedQuantity" placeholder="请输入占用数量" />
      </el-form-item>
      <el-form-item label="已用数量" prop="usedQuantity">
        <el-input v-model="formData.usedQuantity" placeholder="请输入已用数量" />
      </el-form-item>
      <!-- <el-form-item label="剩余可用数量" prop="availableQuantity">
        <el-input v-model="formData.availableQuantity" placeholder="请输入剩余可用数量" />
      </el-form-item> -->
      
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { MaterialStockApi, MaterialStockVO } from '@/api/oa/materialstock'
import MaterialInfoSelect from '@/views/oa/materialinfo/MaterialInfoSelect.vue'
import { MaterialInfoApi } from '@/api/oa/materialinfo'

/** 物品库存明细 表单 */
defineOptions({ name: 'MaterialStockForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  materialId: undefined,
  materialCode: undefined,
  materialName: undefined,
  materialType: undefined,
  unit: undefined,
  totalQuantity: undefined,
  occupiedQuantity: undefined,
  usedQuantity: undefined,
  availableQuantity: undefined,
  creatorName: undefined,
  updaterName: undefined,
})
const formRules = reactive({
  materialId: [{ required: true, message: '物料id不能为空', trigger: 'blur' }],
  materialCode: [{ required: true, message: '物料号不能为空', trigger: 'blur' }],
  materialName: [{ required: true, message: '物料名称不能为空', trigger: 'blur' }],
  materialType: [{ required: true, message: '物料类型不能为空', trigger: 'change' }],
  unit: [{ required: true, message: '单位不能为空', trigger: 'change' }],
  totalQuantity: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  occupiedQuantity: [{ required: true, message: '占用数量不能为空', trigger: 'blur' }],
  usedQuantity: [{ required: true, message: '已用数量不能为空', trigger: 'blur' }],
  availableQuantity: [{ required: true, message: '剩余可用数量不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const materialOptions = ref<any[]>([])

onMounted(async () => {
  const res = await MaterialInfoApi.getMaterialInfoPage({ pageNo: 1, pageSize: 1000 })
  materialOptions.value = res?.list || []
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MaterialStockApi.getMaterialStock(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MaterialStockVO
    if (formType.value === 'create') {
      await MaterialStockApi.createMaterialStock(data)
      message.success(t('common.createSuccess'))
    } else {
      await MaterialStockApi.updateMaterialStock(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    materialId: undefined,
    materialCode: undefined,
    materialName: undefined,
    materialType: undefined,
    unit: undefined,
    totalQuantity: undefined,
    occupiedQuantity: undefined,
    usedQuantity: undefined,
    availableQuantity: undefined,
    creatorName: undefined,
    updaterName: undefined,
  }
  formRef.value?.resetFields()
}
</script>